package com.sinping.qh.api.admin.record;

import com.sinping.qh.api.support.Const;
import com.sinping.qh.api.support.FrontPage;
import com.sinping.qh.api.support.ResDto;
import com.sinping.qh.dto.admin.record.*;
import com.sinping.qh.service.admin.ICheckRecordsService;
import com.sinping.qh.service.common.CommonDbConst;
import com.sinping.qh.utils.mapper.JsonMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 检查记录
 *
 * @author Tiansx
 * @create 2018-06-02 10:52
 **/
@Api(value = "Admin检查管理", description = "Admin检查管理")
@RestController
@RequestMapping(value = Const.ADMIN_URI, name = "检查记录")
@Slf4j
public class RecordEndPoint {
    private final static Logger logger = LoggerFactory.getLogger(RecordEndPoint.class);
    @Autowired
    private ICheckRecordsService iCheckRecordsService;

    @Autowired
    private Validator globalValidator;

    /**
     * 检查记录中亮点删除
     *
     * @param id
     * @return ResDto
     */
    @ApiOperation(value = "检查记录亮点删除", notes = "状态为：检查中的检查记录")
    @RequestMapping(value = "records/highlight/{id}", method = RequestMethod.DELETE, name = "检查记录亮点删除")
    public ResDto deleteHightLight(@ApiParam(name = "id", value = "1234") @PathVariable String id) {


        if (StringUtils.isEmpty(id)) {
            logger.info("必传参数 :{}", "id");
            return new ResDto(Const.PARAM_ERROR, "id");
        }


        return iCheckRecordsService.deleteHightLight(id);


    }

    /**
     * 检查记录亮点修改
     *
     * @param request
     * @param msg
     * @return
     */

    @ApiOperation(value = "检查记录亮点修改", notes = "检查记录状态为：检查中")
    @RequestMapping(value = "records/highlight", method = RequestMethod.PUT, name = "检查记录亮点修改")
    public ResDto updateHightLight(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"id\":\"xxxx\",\"desc\":\"xxxx\"}") @RequestParam(required = true) String msg) {
        HighLightRecordDto apiCheckRecordDto = JsonMapper.defaultMapper().fromJson(msg, HighLightRecordDto.class);
        if (apiCheckRecordDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }

        return iCheckRecordsService.updateHightLight(request, apiCheckRecordDto);


    }


    /**
     * 检查记录中隐患删除
     *
     * @param id
     * @return ResDto
     */
    @ApiOperation(value = "检查记录中隐患删除", notes = "状态为：检查中的检查记录")
    @RequestMapping(value = "records/hidden_danger/{id}", method = RequestMethod.DELETE, name = "检查记录中隐患删除")
    public ResDto deleteHiddenDanger(@ApiParam(name = "id", value = "1234") @PathVariable String id) {


        if (StringUtils.isEmpty(id)) {
            logger.info("必传参数 :{}", "id");
            return new ResDto(Const.PARAM_ERROR, "id");
        }

        return iCheckRecordsService.deleteHiddenDanger(id);


    }

    /**
     * 隐患修改
     *
     * @param request
     * @param msg
     * @return
     */
    @ApiOperation(value = "隐患修改", notes = "检查记录状态为：检查中")
    @RequestMapping(value = "records/hidden_danger", method = RequestMethod.PUT, name = "检查记录隐患修改")
    public ResDto updateHiddenDanger(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"id\":\"隐患id\"," +
            "desc\":\"其他描述\"" +
            ",\"check_item_id\":\"检查项id\"}\n") @RequestParam(required = true) String msg) {
        HiddenDangerInspectItemDto hiddendangerRecordDto = JsonMapper.defaultMapper().fromJson(msg, HiddenDangerInspectItemDto.class);
        if (hiddendangerRecordDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }
        if (StringUtils.isEmpty(hiddendangerRecordDto.getId())){
            return new ResDto(Const.PARAM_ERROR, "隐患id不为空");
        }
        if (StringUtils.isEmpty(hiddendangerRecordDto.getCheckItemId())&& StringUtils.isBlank(hiddendangerRecordDto.getDesc())) {
            return new ResDto(Const.PARAM_ERROR, "请填写或选择隐患描述");
        }
        return iCheckRecordsService.updateHiddenDanger(request, hiddendangerRecordDto);


    }

    /**
     * 修改隐患记录获取检查项列表
     * check_record_type:0-综合检查；1-实验室检查
     */
    @ApiOperation(value = "修改隐患记录获取检查项列表", notes = "检查记录状态为：检查中,check_record_type:0-综合检查；1-实验室检查")
    @RequestMapping(value = "records/hidden_danger", method = RequestMethod.GET, name = "修改隐患记录获取检查项列表")
    public ResDto getHiddenDangerList(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"check_record_type\":\"必填\",\"lab_id\":\"实验室检查,必填，综合检查传空串\"}") @RequestParam(required = true) String msg) {

        ApiInspectItemTreeDto apiInspectItemTreeDto = JsonMapper.defaultMapper().fromJson(msg, ApiInspectItemTreeDto.class);
        if (apiInspectItemTreeDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }

        if (StringUtils.isEmpty(apiInspectItemTreeDto.getCheckRecordType())) {
            return new ResDto(Const.PARAM_ERROR, "检查记录类型不能为空");
        }
        if (CommonDbConst.CHECKRECORD_TYPE_LAB.equals(apiInspectItemTreeDto.getCheckRecordType())) {
            if (StringUtils.isEmpty(apiInspectItemTreeDto.getLabId())) {
                return new ResDto(Const.PARAM_ERROR, "实验室记录lab_id不能为空");
            }
        }

        return iCheckRecordsService.getCheckInspectItemList(request, apiInspectItemTreeDto);


    }


    /**
     * 检查记录提交审核
     */
    @ApiOperation(value = "提交审核", notes = "检查记录状态为：检查中,提交审核")
    @RequestMapping(value = "records/audit", method = RequestMethod.POST, name = "提交审核")
    public ResDto reviewRecord(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"check_record_ids\":[\"id\",\"id\"]}") @RequestParam(required = true) String msg) {

        ApiCheckRecordDto apiCheckRecordDto = JsonMapper.defaultMapper().fromJson(msg, ApiCheckRecordDto.class);
        if (apiCheckRecordDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }

        return iCheckRecordsService.userSubmitRecordsAudit(request, apiCheckRecordDto);
    }

    /**
     * 获取检查待审核记录列表
     * <p>
     * 展示全部待审核检查记录（无数据权限）
     */
    @ApiOperation(value = "获取待审核检查记录列表", notes = "检查记录状态为：待审核, check_status: 2 ,必填")
    @RequestMapping(value = "records", method = RequestMethod.GET, name = "获取待审核检查记录列表")
    public ResDto getWaitedAuditRecordList(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"page_size\":10, \"page_current\":1, \"order_column\":null, " +
            "<br>\"order_by\":null, \"condition\":{\"check_unit_id\":\"log\",\"" +
            "<br>check_building_id\":\"1\",\"check_status\":\"2\"," +
            "<br>\"start_date\":\"1\",\"end_date\":\"1\"}}")
    @RequestParam(required = true) String msg) {
        try {
            logger.info("入参 {}", msg);
            FrontPage page = JsonMapper.defaultMapper().fromJson(msg, FrontPage.class);
            if (page == null) {
                log.info("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "msg.param.error");
            }
            return iCheckRecordsService.getWaitedAuditRecordList(request, page);
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
            return resDto;
        }


    }

    /**
     * 获取检查审核记录详情
     */
    @ApiOperation(value = "获取检查审核记录详情", notes = "检查记录状态为：待审核")
    @RequestMapping(value = "records/{id}", method = RequestMethod.GET, name = "获取检查审核记录详情")
    public ResDto getWaitedAuditRecordDetail(@ApiParam(name = "id", value = "245ad13d6ad4") @PathVariable String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                logger.info("必传参数 :{}", "id");
                return new ResDto(Const.PARAM_ERROR, "id");
            }
            return iCheckRecordsService.getWaitedAuditRecordDetail(id);
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
            return resDto;
        }


    }

    /**
     * 检查记录审核
     *
     * @param request
     * @param msg
     * @return
     */
    @ApiOperation(value = "检查记录审核通过", notes = "检查记录状态为：待审核，check_record_ids：必传项")
    @RequestMapping(value = "records", method = RequestMethod.PUT, name = "检查记录审核通过")
    public ResDto AuditRecord(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"check_record_ids\":[\"id\",\"id\"],\"examine_advice\":\"xxxx\"}") @RequestParam(required = true) String msg) {
        ApiCheckRecordDto apiCheckRecordDto = JsonMapper.defaultMapper().fromJson(msg, ApiCheckRecordDto.class);
        if (apiCheckRecordDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }

        return iCheckRecordsService.auditPass(request, apiCheckRecordDto);
    }

    /**
     * 获取检查记录列表（已审核）
     *
     * @param request
     * @param msg
     * @return
     */
    @ApiOperation(value = "获取检查记录列表（已审核）", notes = "检查记录状态为：已审核, check_status: 3 ,必填")
    @RequestMapping(value = "records/already_audit", method = RequestMethod.GET, name = "获取检查记录列表")
    public ResDto geAlreadyAuditRecordList(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"page_size\":10, \"page_current\":1, \"order_column\":null, " +
            "\"order_by\":null, \"condition\":{\"check_unit_id\":\"log\",\"check_building_id\":\"1\"," +
            "<br>\"check_status\":\"3\",\"check_lab\":\"xxx\"," +
            "<br>\"offices\":\"xxx\",\"start_date\":\"1\",\"end_date\":\"1\"}}")
    @RequestParam(required = true) String msg) {
        try {
            logger.info("入参 {}", msg);
            FrontPage page = JsonMapper.defaultMapper().fromJson(msg, FrontPage.class);
            if (page == null) {
                log.info("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "msg.param.error");
            }
            return iCheckRecordsService.getAlreadyAuditRecordList(request, page);
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
            return resDto;
        }


    }

    /**
     * 记录中图片删除
     *
     * @return ResDto
     */
    @ApiOperation(value = "记录中图片删除")
    @RequestMapping(value = "records/image", method = RequestMethod.DELETE, name = "记录中图片删除")
    public ResDto deleteRecordImage(HttpServletRequest request, @ApiParam(name = "msg", value = "{{\"id\":\"隐患或亮点记录id\"},\"image_id\":\"图片id\",\"type\":\"1:亮点；2：隐患\"}") @RequestParam(required = true) String msg) {
        ApiRecordImageDto apiRecordImageDto = JsonMapper.defaultMapper().fromJson(msg, ApiRecordImageDto.class);
        if (apiRecordImageDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }
        if (StringUtils.isEmpty(apiRecordImageDto.getId())) {
            logger.info("必传参数 :{}", "id");
            return new ResDto(Const.PARAM_ERROR, "id");
        }
        Set<ConstraintViolation<ApiRecordImageDto>> validate = globalValidator.validate(apiRecordImageDto);
        if (!validate.isEmpty()) {
            for (ConstraintViolation<ApiRecordImageDto> apiOrgSalesDTOConstraintViolation : validate) {
                logger.info("必传参数 :{}", apiOrgSalesDTOConstraintViolation.getMessage());
                return new ResDto(Const.PARAM_ERROR, apiOrgSalesDTOConstraintViolation.getMessage());
            }

        }
        return iCheckRecordsService.deleteRecordImage(apiRecordImageDto);


    }



    /**
     * 生成检查报告
     * @param request
     * @param msg
     * @return
     */
    @ApiOperation(value = "生成检查报告word(检查记录)")
    @RequestMapping(value = "records/generate_check_report", method = RequestMethod.GET, name = "检查记录审核")
    public ResDto generateCheckReport(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"check_record_ids\":[\"id\",\"id\"],\"hidden_danger_status\":[\"xxxx\",\"xxxx\"]}") @RequestParam(required = true) String msg) {
        ApiCheckRecordReportDto apiCheckRecordReportDto = JsonMapper.defaultMapper().fromJson(msg, ApiCheckRecordReportDto.class);
        if (apiCheckRecordReportDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }
        if (apiCheckRecordReportDto.getCheckRecordIds()==null){
            return new ResDto(Const.PARAM_ERROR,"check_record_ids不能为空");
        }
        if (apiCheckRecordReportDto.getCheckRecordIds().isEmpty()){
            return new ResDto(Const.PARAM_ERROR,"check_record_ids不能为空");
        }
        if (apiCheckRecordReportDto.getHiddenDangerStatus()==null){
            return new ResDto(Const.PARAM_ERROR,"hidden_danger_status不能为空");
        }
        if (apiCheckRecordReportDto.getHiddenDangerStatus().isEmpty()){
            return new ResDto(Const.PARAM_ERROR,"hidden_danger_status不能为空");
        }
        return iCheckRecordsService.generateCheckReport(apiCheckRecordReportDto);
    }

    /**
     * 打回检查记录
     *
     * @param request
     * @param msg
     * @return
     */
    @ApiOperation(value = "打回", notes = "检查记录状态为：检查中，check_record_ids：必传项")
    @RequestMapping(value = "records/callback", method = RequestMethod.PUT, name = "检查记录审核通过")
    public ResDto callback(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"check_record_ids\":[\"id\",\"id\"]}") @RequestParam(required = true) String msg) {
        logger.info("审核打回 {}", msg);
        ApiCheckRecordDto apiCheckRecordDto = JsonMapper.defaultMapper().fromJson(msg, ApiCheckRecordDto.class);
        if (apiCheckRecordDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }

        return iCheckRecordsService.callback(request, apiCheckRecordDto);
    }
}